package com.zjitc.controller;

import com.zjitc.model.CartItem;
import com.zjitc.model.User;
import com.zjitc.service.CartService;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/26 16:35
 * @description:
 */
@Controller
@RequestMapping("/cart")
public class CartController {

  @Autowired
  private CartService cartService;


  @RequestMapping("/addToCart")
  public String addToCart(
      @RequestParam(name = "pid") String pid,
      @RequestParam(name = "count") Integer count,
      HttpSession session
  ) {
    System.out.println(pid);
    User user = (User) session.getAttribute("users");
    if (user == null) {
      String msg = "请先登录";
      session.setAttribute("msg", msg);
      return "/jsp/login.jsp";
    } else {
      cartService.add(user.getUid(), pid, count);
      return "forward:/cart/addCart.do";
    }
  }

  @RequestMapping("/addCart")
  public String addCart(HttpSession session,Model model) {
    User user = (User) session.getAttribute("users");
    List<CartItem> list = cartService.findAll(user.getUid());
    double total = 0.0;
    for (CartItem item : list) {
      total += item.getTotal();
    }
    session.setAttribute("cart", list);
    session.setAttribute("total", total);
    return "/jsp/cart.jsp";
  }

  @RequestMapping("/removeProduct")
  public String removeProduct(
      @RequestParam(name = "pid")String pid
  ){
    cartService.removeProduct(pid);
    return "forward:/cart/addCart.do";
  }

  @RequestMapping("/clearCart")
  public String clearCart(HttpSession session){
    User user= (User) session.getAttribute("users");
    cartService.clearCart(user.getUid());
    return "forward:/cart/addCart.do";
  }
}
